﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using System.Web;
using System.Configuration;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// WMS方棒订单_同步跟单猿
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WMSSalesInfoToRaipiotController : ControllerBase
    {
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_zh;
        public readonly string con_qh;
        public readonly string con_yb;
        public readonly string con_gz;
        private readonly ILogger _logger;


        public WMSSalesInfoToRaipiotController(ILogger<WMSSalesInfoToRaipiotRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {

            _WMSTokenCheckService = wmsTokenCheckService;
             con= _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            con_gz = _configuration.GetConnectionString("WMSDbConnection_GZ");
            _logger = loggerFactory.CreateLogger<WMSSalesInfoToRaipiotController>();

        }

        /// <summary>
        /// WMS方棒订单_同步跟单猿
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostWMSSalesInfoToGDY([FromBody] WMSSalesInfoToRaipiotRequestDto strparm)
        {
            string factory_code = strparm.factory_code;
            string  strMsg = "";
            object log = "";
            string wms_con = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            List<string> restrSqlList = new List<string>();
            WaybillInfoSendWMSResponseDto re = new WaybillInfoSendWMSResponseDto();
            WaybillInfoSendWMSRequestDto pus = new WaybillInfoSendWMSRequestDto();

            if (factory_code== "C01")
            {
                wms_con = con_zh;
            }
            else if (factory_code == "B01")
            {
                wms_con = con_qh;
            }
            else if (factory_code == "E01")
            {
                wms_con = con_yb;
            }
            else if (factory_code == "G01")
            {
                wms_con = con_gz;
            }
            else
            {

            }

            try
            {
                if (wms_con != "")
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
                    dic = new Dictionary<string, string>(); //查询公用dic
                    dic.Add("organization", "");//查询参数
                    //DataTable push_dt = MethodHelp.GetOutsideTableInfo("TMS0042", dic, wms_con, con);//获取推送数据
                    DataTable push_dt = MethodHelp.GetOutsideTableInfo("TMS0052", dic, wms_con, con);//获取推送数据
                    if (push_dt.Rows.Count > 0)
                    {
                        Dictionary<string, string> urldic = new Dictionary<string, string>(); //查询公用dic
                        urldic = new Dictionary<string, string>(); //查询公用dic
                        urldic.Add("function_description", "跟单猿_Token获取");//查看URL配置表地址描述
                        DataTable token_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                        if (token_dt.Rows.Count > 0)
                        {
                            var reAgv2 = DB.httpGet(token_dt.Rows[0]["interface_url"].ToString(), "", "否");
                            RaipiotTokenResponseDto psp = JsonConvert.DeserializeObject<RaipiotTokenResponseDto>(reAgv2);
                            if (psp.status == 200)
                            {
                                foreach (DataRow item in push_dt.Rows)
                                {

                                    restrSqlList = new List<string>();//回写WMS运单扫码表
                                    ToSalesInfoToRaipiotRequestDto out_info = new ToSalesInfoToRaipiotRequestDto();
                                    List<ToSalesInfoRaipiot_GoodsDetailRequestDto> out_info_de = new List<ToSalesInfoRaipiot_GoodsDetailRequestDto>();
                                    List<ToSalesInfoRaipiot_LoadDetailRequestDto> address_info_de = new List<ToSalesInfoRaipiot_LoadDetailRequestDto>();

                                    //out_info.orderNo = item["sales_order_no"].ToString()+"-"+ item["sales_order_line_no"].ToString();
                                    out_info.orderNo = item["sales_order_no"].ToString();
                                    out_info.orderType = "CONSIGNMENT";
                                    out_info.createUserNumber = "systms";
                                    out_info.requiredDeliveryTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();


                                    dic = new Dictionary<string, string>(); //查询公用dic
                                    dic.Add("factory_code", item["factory_code"].ToString());
                                    DataTable dt_start = MethodHelp.GetTableInfo("TMS0044", dic, con);//获取发货地信息
                                    if (dt_start.Rows.Count>0)
                                    {
                                        address_info_de.Add(new ToSalesInfoRaipiot_LoadDetailRequestDto
                                        {
                                            deliverCompanyCode = dt_start.Rows[0]["factory_number"].ToString(),
                                            loadType = "PLACE_OF_SHIPMENT",
                                            originalPhone = dt_start.Rows[0]["contact_phone"].ToString(),
                                            deliverUserName = dt_start.Rows[0]["contact_man"].ToString(),
                                            deliverCompanyName = dt_start.Rows[0]["factory_fullname"].ToString(),
                                            loadAddress = dt_start.Rows[0]["factory_address"].ToString()
                                        });
                                    }


                                    dic = new Dictionary<string, string>(); //查询公用dic
                                    dic.Add("customer_name", item["customer_name"].ToString());
                                    DataTable dt_end = MethodHelp.GetTableInfo("TMS0045", dic, con);//获取发货地信息
                                    if (dt_end.Rows.Count > 0)
                                    {
                                        address_info_de.Add(new ToSalesInfoRaipiot_LoadDetailRequestDto
                                        {
                                            deliverCompanyCode = dt_end.Rows[0]["factory_number"].ToString(),
                                            loadType = "RECEIPT_SHIPMENT",
                                            originalPhone = dt_end.Rows[0]["contact_phone"].ToString(),
                                            deliverUserName = dt_end.Rows[0]["contact_man"].ToString(),
                                            deliverCompanyName = dt_end.Rows[0]["factory_fullname"].ToString(),
                                            loadAddress = dt_end.Rows[0]["factory_address"].ToString()
                                        });
                                    }


                                    dic = new Dictionary<string, string>(); //查询公用dic
                                    dic.Add("sales_order_no", item["sales_order_no"].ToString());
                                    DataTable dt_sod = MethodHelp.GetOutsideTableInfo("TMS0053", dic,wms_con,con);
                                    if (dt_sod.Rows.Count>0)
                                    {
                                        foreach (DataRow row in dt_sod.Rows)
                                        {
                                            out_info_de.Add(new ToSalesInfoRaipiot_GoodsDetailRequestDto
                                            {
                                                goodsName = row["material_name"].ToString(),
                                                goodsCode = row["material_code"].ToString(),
                                                count = row["material_amount"].ToString(),
                                                saleNo = row["sales_order_no"].ToString(),
                                                subOrderNo = row["sales_order_line_no"].ToString(),
                                                unit = row["material_unit"].ToString()

                                            });


                                            dic = new Dictionary<string, string>(); //查询公用dic
                                            dic.Add("id", row["id"].ToString());
                                            string strSQL = MethodHelp.GetTranSQL("TMS0043", dic, con);//转换插入任务执行明细表SQL语句
                                            if (strSQL == "")
                                            {
                                                strMsg = "TMS0043,Parameter conversion failed";
                                            }
                                            else
                                            {
                                                restrSqlList.Add(strSQL.ToString());
                                            }
                                        }
                                       
                                    }                                                                     
                                    if (out_info_de.Count > 0&& address_info_de.Count>0)
                                    {
                                        out_info.consignmentNoteOrderGoodsAddRequests = out_info_de;
                                        out_info.consignmentNoteOrderLoadAddRequests = address_info_de;

                                        urldic = new Dictionary<string, string>(); //查询公用dic
                                        urldic.Add("function_description", "跟单猿_运输需求新增");//查看URL配置表地址描述
                                        DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                        if (url_dt.Rows.Count > 0)
                                        {
                                            string jsonText = JsonConvert.SerializeObject(out_info);
                                            var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, psp.data.token, "是");
                                            ToRaipiotInfoResponseDto psp2 = JsonConvert.DeserializeObject<ToRaipiotInfoResponseDto>(reAgv);
                                            if (psp2.status != 200)
                                            {
                                                strMsg = strMsg + "-" + "跟单猿 ERR:" + "运单：" + out_info.orderNo + psp2.message;
                                            }
                                            else
                                            {
                                                if (restrSqlList.Count > 0)
                                                {
                                                    bool A = DB.ExecuteNoQueryTran(restrSqlList, wms_con);
                                                    if (A)
                                                    {

                                                    }
                                                    else
                                                    {
                                                        strMsg = "HandleTaskUpdate  Database update failed";
                                                    }
                                                }

                                            }
                                        }
                                    }

                                }
                            }
                           
                        }                    
                    }
                }
               
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                re.code = 0;
               
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }

            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);
        }

      
    }
}
